<template>
	<view class="content_page" v-if="!showError">
		<div class="tab_box">
			<div class="flex_between" :class="['plan_tab', globalFont]">
				<div class="plan_tab_item" :style="{ width: tabListWidth[tabList.length] }"
					:class="{ activeTab: i.label == activeTab }" v-for="(i, k) in tabList" :key="k"
					@click="tabActive(i)">
					{{ i.label }}
				</div>
			</div>
			<!-- 延时xx -->
			<div class="flex_between" :class="['delay_work', globalFont]">
				<div class="delay_title">
					延时{{ activeTab.slice(0, activeTab.length - 2) }}
				</div>
				<div style="display: none">{{ activeTab }}</div>
				<div style="display: flex">
					<div class="delay_box" v-for="(i, k) in worktime" :key="k" @click="getdelayTime(i)" :class="{
						activeDelayTab: i.isSelected,
						disabledClass: planboxList.planList.length == 0 || planboxList.planList.every(item => !item.enableStatus)
					}">
						{{ i.title }}小时
						<image src="/static/home/icon_Selected@2x.png" v-if="i.isSelected"></image>
					</div>
				</div>
			</div>
		</div>
		<div class="warning_box" v-if="activeDelayTab != 0">
			<image src="/static/home/icon_jingao@2x.png"></image>
			<div :class="['warning_title', globalFont]">
				延时计划：{{ delayworkTime }}后设备正常执行计划
			</div>
		</div>
		<div class="circle_plan">
			<!-- 循环区域 -->
			<scroll-view scroll-y="true" class="scroll-Y">
				<div class="circle_plan_item" v-for="(i, k) in planboxList.planList" :key="k">
					<div style="padding: 40rpx 32rpx 0">
						<div class="plan_switch_box">
							<div v-if="i.planName" :class="['title', globalFont]">{{ i.planName }}</div>
							<!-- activeTab.slice(0, activeTab.length - 2) -->
							<div :class="['title', globalFont]" v-else>{{ activeTab }}{{ k + 1 }}</div>
							<div class="title_span"></div>
							<up-switch v-model="i.enableStatus" activeColor="#006D56"
								@change="editChange(i)"></up-switch>
						</div>
						<div class="info_box flex_between">
							<div class="item_box">
								<div>
									<image src="/static/home/wusen.png" v-if="activeTab == '雾森计划'"></image>
									<image src="/static/home/quwen.png" v-if="activeTab == '驱蚊计划'"></image>
									<image src="/static/home/jiangwen.png" v-if="activeTab == '降温计划'"></image>
								</div>
								<div :class="['tip', globalFont]">
									{{ activeTab.slice(0, activeTab.length - 2) }}时长：{{ handleArr(i.workTime) }}
								</div>
							</div>
							<div class="item_box">
								<image src="/static/home/device_icon_interval@2x.png" v-if="activeTab !== '驱蚊计划'">
								</image>
								<div class="icon start" v-if="activeTab == '驱蚊计划'" :style="{ marginLeft: globalFont == 'small_font' ? '' : '5rpx' }"></div>
								<div :class="['tip', globalFont]" v-if="activeTab !== '驱蚊计划'">
									间歇时长：{{ handleArr(i.restTime) }}
								</div>
								<div :class="['tip', globalFont]" v-if="activeTab == '驱蚊计划'">
									开始时间:{{ i.startTime }}
								</div>
							</div>
						</div>
						<div class="flex_between" v-if="activeTab !== '驱蚊计划'">
							<div class="item_box">
								<div class="icon start" :style="{ marginLeft: globalFont == 'small_font' ? '' : '10rpx' }"> </div>
								<div :class="['tip', globalFont]">开始时间：{{ i.startTime }}</div>
							</div>
							<div class="item_box">
								<div class="icon end" :style="{ marginLeft: globalFont == 'small_font' ? '' : '10rpx' }"></div>
								<div :class="['tip', globalFont]" >结束时间：{{ i.endTime }}</div>
							</div>
						</div>
						<div class="info_box" :style="{ marginTop: globalFont == 'small_font' ? '10rpx' : '0' }">
							<image src="/static/home/interval_icon_calendar@2x.png"
								:style="{ marginTop: globalFont == 'small_font' ? '5rpx' : '12rpx' }"></image>
							<div :class="['tip', globalFont]">周历计划：{{ getweekName(i.workday) }}</div>
						</div>
					</div>
					<div class="action_box flex_between">
						<div class="action_empty"></div>
						<div class="action_btn flex_center" @click="toaddEditPage(i.planId, i, k)">
							<image src="/static/home/icon_edit@2x.png"></image>
							<div :class="['title', globalFont]">编辑</div>
						</div>
						<div class="action_btn flex_center" @click="delPlan(i.planId)">
							<image src="/static/home/icon_delete@2x.png"></image>
							<div :class="['title', globalFont]">删除</div>
						</div>
					</div>
				</div>
				<!-- 添加计划 -->
				<div class="addnewPlan">
					<image src="/static/home/icon_tianjia@2x.png"></image>
					<div :class="['title', globalFont]" @click="toaddEditPage(0, null, null)">
						新增{{ activeTab }}
					</div>
				</div>
			</scroll-view>
			<div class="delModal">
				<up-modal :show="show" :showCancelButton="true" title="提示" content="您确定要删除该计划吗" @confirm="confirmModal"
					@cancel="show = false"></up-modal>
			</div>
			<!-- 开启关闭延时 -->
			<div class="delModal">
				<up-modal :show="delayModal.visiable" :showCancelButton="true" title="提示" :content="delayModal.content"
					@confirm="confirmDelayModal" @cancel="delayModal.visiable = false"></up-modal>
			</div>
		</div>
	</view>
	<view class="content_page_error" v-if="showError">
		<image src="/src/static/Index/error.png"></image>
		<div class="text">设备出现异常，无法查看详情请联系设备管理员</div>
		<div class="content_page_btn">
			<div class="one" @click="getData">再试一次</div>
		</div>
	</view>
</template>

<script setup lang="ts">
import { ref, defineProps, onMounted, getCurrentInstance } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import type { devicePlanType } from "@api/detail/type.ts";
import {
	deviceplanDetail,
	devicePlanDelayFn,
	editPlanStatus,
	deldevicePlan,
} from "../api/detail/detail.ts";
const instance = getCurrentInstance();
const appStorage = instance?.appContext.config.globalProperties.appStorage; // 获取全局变量
const planboxList = ref<devicePlanType>({
	delayTime: "", //延迟时间
	planList: [
		{
			sprayModel: "2",
			planId: null,
			planName: "",
			startTime: "",
			endTime: "",
			workTime: "",
			restTime: "",
			enableStatus: false,
			workday: "",
		},
	],
});
const delayModal = ref({
	visiable: false,
	content: ''
})
const tabList = ref<{ label: string; value: string }[]>([]);
const propData = defineProps(["equipmentId", "workType", "currentSprayModal"]);
const activeTab = ref<string>("");
const sprayModelTab = ref("2");
const showError = ref(false);
const isTabFnExecuted = ref(false)
const getData = () => {
	// if (!isTabFnExecuted.value) {
	// 	activeTabFn();
	// 	}
	// planboxList.value = {
	// 	delayTime: "24",
	// 	workType: '1,2,6',
	// 	expirationTime:"2025-05-29 14:06:14",
	// 	planList: [
	// 		{
	// 			enableStatus: true,
	// 			endTime: "23:10",
	// 			equipmentId: null,
	// 			planId: 516,
	// 			planName: "aa",
	// 			restTime: "1:0",
	// 			sprayModel: 1,
	// 			startTime: "14:00",
	// 			workTime: "1:0",
	// 			workday: "3;4",
	// 		},
	// 		{
	// 			enableStatus: false,
	// 			endTime: "14:00",
	// 			equipmentId: null,
	// 			planId: 517,
	// 			planName: "雾森计划1",
	// 			restTime: "11:9",
	// 			sprayModel: 1,
	// 			startTime: "14:00",
	// 			workTime: "2:0",
	// 			workday: "1;2;3",
	// 		}
	// 	],
	// };
	// activeTabFn()
	// activeDelayTab.value = planboxList.value.delayTime || 0;
	// worktime.value = worktime.value.map((f) => {
	// 	if (f.title == planboxList.value.delayTime) {
	// 		f.isSelected = true;
	// 	} else if (planboxList.value.delayTime === 0) {
	// 		// 处理 delayTime 为 0 的情况
	// 		f.isSelected = false;  // 或者其他逻辑
	// 	}
	// 	return { ...f };
	// });
	// return;
	// 调用接口	 
	// sprayModelTab.value = propData.workType.split(',')[0];
	const sprayModel = (!isTabFnExecuted.value)
		? (propData.currentSprayModal ? propData.currentSprayModal : propData.workType.split(',')[0])
		: sprayModelTab.value;
	deviceplanDetail({
		equipmentId: propData.equipmentId,
		sprayModel: sprayModel,
	})
		.then((res: any) => {
			if (res.resultStatus) {
				planboxList.value = res.resultData;
				activeDelayTab.value = planboxList.value.delayTime || 0;
				worktime.value = worktime.value.map((f) => {
					if (f.title == planboxList.value.delayTime) {
						f.isSelected = true;
					} else if (planboxList.value.delayTime === 0) {
						f.isSelected = false;
					}
					return { ...f };
				});
				const statusAll = planboxList.value.planList.every(item => !item.enableStatus) || !planboxList.value.planList.length;
				if (statusAll) {
					activeDelayTab.value = 0
					worktime.value.forEach(item => item.isSelected = false);
				}
				delayworkTime.value = removeYearAndSeconds(planboxList.value.expirationTime)				
				// delayworkTime.value = planboxList.value.expirationTime||"2025-05-29 14:06:14"
				if (!isTabFnExecuted.value) {
					activeTabFn();
				}
			} else {
				uni.showToast({
					title: res.errorMessage,
					icon: "none",
				});
			}
		})
		.catch((err: any) => {
			showError.value = true;
			uni.showToast({
				title: "服务器异常",
				icon: "none",
			});
		})
		.finally(() => {
		});
};
// 年份处理
const removeYearAndSeconds = (str:String) => {
const date = new Date(str);
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  // 返回格式化后的日期字符串（去掉年份和秒数）
  return `${month}-${day} ${hours}:${minutes}`;
}
// tab切换
const tabActive = (type: any) => {
	isTabFnExecuted.value = true;
	sprayModelTab.value = type.value;
	activeTab.value = type.label;
	worktime.value.forEach((item) => {
		item.isSelected = false;
	});
	getData();
};
const handleArr = (string: string) => {
	if (!string) {
		return "";
	}
	const res = string.split(":");
	return `${res[0]}分${res[1]}秒`;
};
// 延时
const worktime = ref<{ id: string; title: string; isSelected: Boolean }[]>([
	{
		id: "1",
		title: "24",
		isSelected: false,
	},
	{
		id: "1",
		title: "48",
		isSelected: false,
	},
]);
const SprayMode = ref([
	{
		id: "1",
		title: "喷雾",
	},
	{
		id: "2",
		title: "驱蚊",
	},
]);
const tabListWidth: { [key: number]: string } = {
	1: "100%",
	2: "48%",
	3: "30%",
};
// 修改switch
const editChange = (k: any) => {
	uni.showLoading({
		title: "操作中...",
		icon: 'none'
	})
	editPlanStatus({
		equipmentId: Number(propData.equipmentId),
		planId: k.planId,
		enableStatus: k.enableStatus,
	})
		.then((res: any) => {
			if (res.resultStatus) {
				uni.showToast({
					title: "操作成功",
					icon: "none",
				});
				getData();
			} else {
				k.enableStatus = !k.enableStatus;
				uni.showToast({
					title: res.errorMessage,
					icon: "none",
					duration: 3000
				});
				setTimeout(() => {
					getData();
				}, 3000);
			}
		})
		.catch((err: any) => {
			console.log(err);
			uni.showToast({
				title: "服务器异常",
				icon: "none",
			});
		}).finally(() => {
			setTimeout(() => {
				uni.hideLoading();
			}, 500);
		});
};
//设备延时
const activeDelayTab = ref<string>('0');
const delayworkTime = ref<string>("");
const selectedItem = ref();
const getdelayTime = (i: any) => {
	if (planboxList.value.planList.length == 0 || planboxList.value.planList.every(item => !item.enableStatus)) {
		uni.showToast({
			title: "请先设置计划",
			icon: "none",
		})
		return
	}
	selectedItem.value = i;
	delayModal.value.content = i.isSelected ? '是否确认关闭延时' : '是否确认开启延时';
	delayModal.value.visiable = true;
};
const confirmDelayModal = () => {
	if (!selectedItem.value) {
		return;
	}
	const i = selectedItem.value;
	const originalWorktime = JSON.parse(JSON.stringify(worktime.value));
	if (i.isSelected) {
		i.isSelected = false;
	} else {
		// 取消其他项的选中状态
		worktime.value.forEach((item) => {
			item.isSelected = false;
		});
		i.isSelected = true;
	}
	const delayTime = i.isSelected ? Number(i.title) : 0;
	uni.showLoading({
		title: "操作中...",
		icon: 'none'
	});
	devicePlanDelayFn({
		equipmentId: propData.equipmentId,
		delayTime: delayTime,
		sprayModel: sprayModelTab.value,
	})
		.then((res: any) => {
			if (res.resultStatus) {
				uni.showToast({
					title: "操作成功",
					icon: "none",
				});
				getData();
			} else {
				uni.showToast({
					title: res.errorMessage,
					icon: "none",
					duration: 4000,
				});
				worktime.value = originalWorktime;
			}
		})
		.catch((err: any) => {
			console.log(err);
			uni.showToast({
				title: "服务器异常",
				icon: "none",
			});
		})
		.finally(() => {
			setTimeout(() => {
				delayModal.value.visiable = false
				uni.hideLoading();
			}, 500);
		});
};
// 喷洒模式
const sprayActive = ref<string>("");
const toSprayMode = (id: string) => {
	sprayActive.value = id;
	devicePlanDelayFn({
		equipmentId: propData.equipmentId,
		sprayModel: id,
	})
		.then((res: any) => {
			if (res.resultStatus) {
				uni.showToast({
					title: "操作成功",
					icon: "none",
				});
			} else {
				uni.showToast({
					title: res.errorMessage,
				});
			}
		})
		.catch((err: any) => {
			uni.showToast({
				title: "服务器异常",
				icon: "none",
			});
		});
};
// 周历计划
const getweekName = (k: string) => {
	const weekPlan: { [key: string]: string } = {
		"1": "周一",
		"2": "周二",
		"3": "周三",
		"4": "周四",
		"5": "周五",
		"6": "周六",
		"7": "周日",
	};
	const weekArr = k?.split(";").sort((a: any, b: any) => a - b);
	if (weekArr.length === 7 && weekArr.every((num) => weekPlan[num])) {
		return "周一到周日";
	}
	return weekArr.map((num) => weekPlan[num] || "").join("、");
};
// 新增编辑计划
const toaddEditPage = (id: number | string, info: any, index: number) => {
	uni.navigateTo({
		url: `/pages/setDevice/addNew?&equipmentId=${propData.equipmentId}&sprayModel=${sprayModelTab.value}&planId=${id}&planName=${info?.planName}&startTime=${info?.startTime}&endTime=${info?.endTime}&workTime=${info?.workTime}&restTime=${info?.restTime}&workday=${info?.workday}&enableStatus=${info?.enableStatus}&length=${planboxList.value.planList.length}&index=${index}`,
	});
};
// 删除计划
const show = ref<boolean>(false);
let planId: any = null;
let equipmentId: any = null;
const delPlan = (id: number) => {
	planId = id;
	equipmentId = Number(propData.equipmentId);
	show.value = true;
};
const confirmModal = () => {
	uni.showLoading({
		title: "删除中...",
		icon: "none",
	});
	deldevicePlan({
		equipmentId: equipmentId,
		planId: planId,
	})
		.then((res: any) => {
			if (res.resultStatus) {
				uni.showToast({
					title: "删除成功",
					icon: "none",
				});
				getData();
			} else {
				uni.showToast({
					title: res.errorMessage,
					icon: "none",
					duration: 3000
				});
				setTimeout(() => {
					getData();
				}, 3000);
			}
		})
		.catch((err: any) => {
			uni.showToast({
				title: "服务器异常",
				icon: "none",
			});
		})
		.finally(() => {
			show.value = false;
			setTimeout(() => {
				uni.hideLoading();
			}, 300);
		});
};
// 默认选中tab
const activeTabFn = () => {
	const customOrder = [2, 1, 6];  // 自定义的顺序
	const workTypeIds: string[] = planboxList.value.workType?.split(","); // 将字符串转为数组
	workTypeIds?.sort((a, b) => {
		return customOrder.indexOf(parseInt(a)) - customOrder.indexOf(parseInt(b));
	});
	const tabMap: Record<string, string> = {
		"1": "雾森计划",
		"2": "驱蚊计划",
		"6": "降温计划",
	};
	let arr = workTypeIds.map((id) => ({
		label: tabMap[id],
		value: id,
	}));
	tabList.value = arr;
	if (planboxList.value.categoryName !== 'NSW-002' && !planboxList.value.temperatureStatus) {
		tabList.value = arr.filter(type => type.value != 6);
	}
	if (propData.currentSprayModal) {
		console.log(tabList.value, 'tabList.value');
		sprayModelTab.value = propData.currentSprayModal;
		const k = tabList.value.filter((i) => i.value == sprayModelTab.value)[0]
			.label;
		activeTab.value = k;
	} else {
		sprayModelTab.value = tabList.value[0].value;
		activeTab.value = tabList.value[0].label;
	}
};
const globalFont = ref()
onMounted(() => {
	getData();
	const userInfo = appStorage.getObj("userInfo_key");
	globalFont.value = userInfo.smallFont
});
</script>
<style scoped lang="scss">
:root {
	/* 默认字号 */
	--font-size-small: 26rpx;
	// 默认radio自豪
	--font-size-radio-small: 20rpx;
	/* 中号字号 */
	--font-size-medium: 34rpx;
	--font-size-large: 40rpx;
	/* 大号字号 */
}

.small_font {
	font-size: var(--font-size-small);
}

.small-medium {
	font-size: var(--font-size-medium);
}

.small-large {
	font-size: var(--font-size-large);
}

.content_page {
	height: calc(100vh - 63rpx);
	// padding-bottom: 160rpx;
	overflow: hidden;

	&_btn {
		margin: 110rpx auto;

		.one {
			width: 500rpx;
			height: 88rpx;
			background: linear-gradient(90deg, #00a67e, #006d56);
			line-height: 88rpx;
			text-align: center;
			border-radius: 44rpx;
			margin-bottom: 30rpx;
			color: #fff;
		}
	}

	.tab_box {
		padding: 50rpx 40rpx;
		background-color: #fff;

		.plan_tab {
			height: 70rpx;
			background: #f5f6f7;
			border-radius: 16rpx;
			padding: 10rpx;

			.plan_tab_item {
				line-height: 70rpx;
				text-align: center;
				background-color: #f5f6f7;
				// font-size: 24rpx;
				border-radius: 10rpx;
			}

			.activeTab {
				// font-size: 24rpx;
				font-weight: bold;
				text-align: center;
				color: #006d56;
				line-height: 70rpx;
				background-color: #fff;
				border: 2px solid #fff;
			}
		}

		.delay_work {
			height: 88rpx;
			margin-top: 32rpx;

			.delay_box {
				width: 210rpx;
				height: 88rpx;
				line-height: 88rpx;
				text-align: center;
				// font-size: 24rpx;
				border: 2rpx solid #efefef;
				border-radius: 16px;
				margin-left: 30rpx;
				position: relative;

				image {
					width: 38rpx;
					height: 32rpx;
					position: absolute;
					top: 0;
					right: 0;
				}
			}

			.activeDelayTab {
				border: 2rpx solid #00a57d;
			}

			.disabledClass {
				background: #f5f5f5;
			}

			.delay_title {
				// font-size: 24rpx;
				color: #333;
				font-weight: bold;
			}
		}
	}

	.warning_box {
		// width: 100%;
		// height: 56rpx;
		// line-height: 56rpx;
		background-color: rgb(250, 237, 237);
		padding: 10rpx 30rpx;
		display: flex;
		align-items: center;

		image {
			width: 32rpx;
			height: 32rpx;
			margin-right: 12rpx;
		}

		.warning_title {
			// font-size: 24rpx;
			text-align: left;
			color: #c92a2a;
		}
	}

	.circle_plan {
		padding: 32rpx;
		background-color: #f5f6f7;
		height: calc(100% - 500rpx);

		.scroll-Y {
			height: 100%;
			margin-bottom: 100rpx;
		}

		.circle_plan_item {
			background: #ffffff;
			border-radius: 16rpx;
			margin-bottom: 20rpx;

			.plan_switch_box {
				position: relative;
				display: flex;
				justify-content: space-between;
				margin-bottom: 40rpx;

				.title {
					// font-size: 24rpx;
					color: #000;
					font-weight: bold;
				}

				.title_span {
					position: absolute;
					left: -32rpx;
					top: 2rpx;
					width: 4px;
					height: 40rpx;
					background: #00a57d;
					border-radius: 0 4rpx 4rpx 0;
				}
			}

			.info_box {
				display: flex;
				align-items: flex-start;

				image {
					// margin-top: 8rpx;
				}


				.icon {
					width: 16rpx;
					height: 16rpx;
					border-radius: 50%;
				}

				.start {
					background: #00d392;
					// margin-right: 23rpx;
				}

				.end {
					background: #c92a2a;
					width: 16rpx;
					margin-right: 23rpx;
				}

				image {
					width: 30rpx;
					height: 30rpx;
					margin-right: 10rpx;
				}

				.tip {
					// font-size: 24rpx;
				}
			}

			.action_box {
				height: 100rpx;
				border-top: 2rpx solid #eeeeee;
				margin-top: 40rpx;

				.action_empty {
					width: 260rpx;
					height: 100%;
				}

				.action_btn {
					padding-right: 54rpx;

					image {
						width: 24rpx;
						height: 24rpx;
						margin-right: 20rpx;
					}

					.title {
						// font-size: 24rpx;
						text-align: left;
						color: #666666;
						line-height: 40rpx;
					}
				}
			}
		}

		.addnewPlan {
			height: 88rpx;
			line-height: 88rpx;
			background-color: #fff;
			border-radius: 16px;
			display: flex;
			justify-content: center;
			align-items: center;
			text-align: center;

			image {
				width: 24rpx;
				height: 24rpx;
				margin-right: 20rpx;
			}

			.title {
				// font-size: 24rpx;
				color: #333333;
			}
		}
	}
}

.content_page_error {
	height: 100vh;
	display: flex;
	flex-direction: column;
	justify-content: flex-start;
	align-items: center;
	background: #f5f6f7;

	image {
		width: 280rpx;
		height: 220rpx;
		margin-top: 160rpx;
	}

	.text {
		width: 300rpx;
		height: 80rpx;
		font-size: 24rpx;
		text-align: center;
		color: #999999;
		line-height: 40rpx;
	}
}

.item_box {
	text-align: left;
	margin-bottom: 5rpx;
	display: flex;
	align-items: center;

	image {
		vertical-align: middle;
	}
	.start{
		margin-right: 18rpx;
		background-color: #00D392;
	}
	.end{
		margin-right: 18rpx;
		background-color: #C92A2A;
	}
	.icon{
		width: 16rpx;
		height: 16rpx;
		border-radius: 50%;
	}
}

.flex_between {
	display: flex;
	justify-content: space-between;
	flex-wrap: wrap;
	align-items: center;
}
</style>